using System;
using System.Net;
using System.Web;

using Google.Apps.Provisioning.Utilities;

namespace Google.Apps.Provisioning.Authentication
{
    /// <summary>
    /// Manages all interaction with the authentication subsystem.  Any consumers of this API should
    /// use this class for all API calls.
    /// </summary>
    public class AuthenticationManager
    {
        /// <summary>
        /// Calls Google's ClientLogin interface to receive a security token for the specified user.
        /// </summary>
        /// <param name="email">Email address of the account to retrieve a token for.</param>
        /// <param name="password">Password of the account to a retrieve a token for.</param>
        /// <exception cref="GoogleAuthenticationException">If the user's login is invalid (unknown 
        /// user, incorrect password, etc), a GoogleAuthenticationException is thrown.</exception>
        public static string GetSecurityToken( string email, string password )
        {
            string postBody = string.Format(
                "accountType=HOSTED&Email={0}&Passwd={1}",
                HttpUtility.UrlEncode( email ),
                HttpUtility.UrlEncode( password ) );

            string targetUrl = "https://www.google.com/accounts/ClientLogin";

            string result;
            HttpStatusCode status;

            // TODO: do we need to handle CAPTCHA case, and if so, how?
            WebUtility.DoHttpPost( targetUrl, postBody, out status, out result );

            string sid = string.Empty;
            string lsid = string.Empty;

            foreach( string token in result.Split( '\n' ) )
            {
                if ( token.StartsWith( "SID=" ) )
                {
                    sid = token.Substring( 4 );
                }
                else if ( token.StartsWith( "LSID=" ) )
                {
                    lsid = token.Substring( 5 );
                }
                else
                {
                    if ( token.Trim().Length > 0 )
                    {
                        throw new GoogleAuthenticationException( 
                            string.Format( 
                                "Error authenticating Google user '{0}'.  (Result={1})", 
                                email, 
                                result ) );
                    }
                }
            }

            return sid;
        }
    }
}
